import { i18n } from '@/i18n/index.js'
import { getToken } from '@/utils/auth.js'
import axios from 'axios'
import {useUserStore} from "@/store/modules/user.js";

const { t, locale } = i18n.global

const errorCodeMap = {
  502: '网关错误',
  503: '服务不可用',
  504: '网关超时',
}

const service = axios.create({
  baseURL:
    import.meta.env.DEV
      && (import.meta.env.VITE_OPEN_PROXY === 'true'
        ? '/proxy/'
        : import.meta.env.VITE_APP_API_BASEURL),
  timeout: 1000 * 60,
  responseType: 'json',
})

service.interceptors.request.use(
  (config) => {
    if (config.headers) {
      if (getToken()) {
        config.headers.Authorization = `Bearer ${getToken()}`
      }
    }
    return config
  },
  (error) => {
    console.error('Request Error:', error.message || '请求错误')
    window.$message?.error(error.message || '请求错误')
    return Promise.reject(error.message || '请求错误')
  },
)

service.interceptors.response.use(
  (response) => {
    const { data } = response
    const { code, msg } = data
    const userStore = useUserStore()
    if (typeof code !== 'undefined' && code !== 200) {
      const errorMessage = errorCodeMap[code] || msg || '未知错误'
      switch (code) {
        case 401:
          userStore.logout()
          break
        case 403:
          // 无权限
          break
        default:
          window.$message?.error(errorMessage)
          break
      }
      return Promise.reject(new Error(errorMessage))
    }
    return data
  },
  (error) => {
    const message = error.response
      ? errorCodeMap[error.response.status] || error.response.statusText
      : error.message || '请求错误'
    console.error('Response Error:', message)
    window.$message?.error(message)
    return Promise.reject(message)
  },
)

const request = {
  get(url, data, requestBaseUrl) {
    return request.request('GET', url, { params: data }, requestBaseUrl)
  },

  post(url, data, requestBaseUrl) {
    return request.request('POST', url, { data }, requestBaseUrl)
  },

  upload(url, data, requestBaseUrl) {
    const headers = { 'Content-Type': 'multipart/form-data' }
    return request.request('POST', url, { data, headers, requestBaseUrl })
  },
  put(url, data, requestBaseUrl) {
    return request.request('PUT', url, { data }, requestBaseUrl)
  },
  delete(url, data, requestBaseUrl) { return request.request('DELETE', url, { data }, requestBaseUrl) },
  request(method = 'GET', url, data = {}, requestBaseUrl) {
    return new Promise((resolve, reject) => {
      const config = { method, url, ...data }
      if (requestBaseUrl) {
        config.baseURL = requestBaseUrl
      }

      service(config)
        .then((res) => {
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
}

export default request
